package sing.flutter

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.DisplayMetrics
import android.util.Log
import com.baidu.ocr.sdk.OCR
import com.baidu.ocr.sdk.OnResultListener
import com.baidu.ocr.sdk.exception.OCRError
import com.baidu.ocr.sdk.model.IDCardParams
import com.baidu.ocr.sdk.model.IDCardResult
import com.baidu.ocr.ui.camera.CameraActivity
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.CSJAdError
import com.bytedance.sdk.openadsdk.CSJSplashAd
import com.bytedance.sdk.openadsdk.TTAdConfig
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdLoadType
import com.bytedance.sdk.openadsdk.TTAdNative.CSJSplashAdListener
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTCustomController
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import sing.core.callback.Callback
import sing.core.ext.util.dp2px
import sing.core.ext.util.getStrTime
import sing.core.ext.util.loge
import sing.core.ext.util.px2dp
import sing.core.ext.util.screenHeight
import sing.core.ext.util.screenWidth
import sing.core.ext.util.statusBarHeight
import sing.core.util.FileUtils
import sing.myapp.R
import java.io.File


class MainActivity: FlutterActivity() {

    var plugin : FlutterPlugin? = null
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        GeneratedPluginRegistrant.registerWith(flutterEngine)
        plugin = FlutterPlugin.registerWith(flutterEngine, this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        plugin?.setCallback(object :Callback{
            override fun result(vararg data: Any) {
//                PocketSdk.initSDK(context, "xiaomi", "1");

                // 初始化穿山甲
                TTAdSdk.init(this@MainActivity, buildConfig())

                TTAdSdk.start(object : TTAdSdk.Callback {
                    override fun success() {
                        "success: ${TTAdSdk.isSdkReady()}".loge()
                        // 可以展示广告了
                        start()
                    }

                    override fun fail(code: Int, msg: String) {
                        "fail:  code = $code msg = $msg".loge()
                        FlutterPlugin.toFlutter("loadAdOver","")
                    }
                })
            }
        })
        plugin?.setIdCardCallback(object :Callback{
            override fun result(vararg data: Any) {
                val intent = Intent(this@MainActivity, ScanIdActivity::class.java)
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, FileUtils.getSaveFile(application).absolutePath)
                intent.putExtra(CameraActivity.KEY_NATIVE_ENABLE, true)
                intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true)
                if (data[0] as Boolean){
                    intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT)
                }else{
                    intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK)
                }
                startActivityForResult(intent, 888)
            }
        })
    }

    private fun buildConfig(): TTAdConfig {
        return TTAdConfig.Builder()
            .appId("5524370")//xxxxxxx为穿山甲媒体平台注册的应用ID
            .useTextureView(true) //默认使用SurfaceView播放视频广告,当有SurfaceView冲突的场景，可以使用TextureView
            .allowShowNotify(true) //是否允许sdk展示通知栏提示,若设置为false则会导致通知栏不显示下载进度，存在违规风险，请勿随意更改
            .debug(true) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
            .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI) //允许直接下载的网络状态集合,没有设置的网络下点击下载apk会有二次确认弹窗，弹窗中会披露应用信息
            .supportMultiProcess(false) //是否支持多进程，true支持
            .customController(object : TTCustomController() {
                override fun isCanUseLocation() = false // 是否允许SDK主动使用地理位置信息
                override fun getTTLocation() = null
                override fun isCanUsePhoneState() = false // 是否允许SDK主动使用手机硬件参数，如：imei
                override fun getDevImei() = "" // 当isCanUsePhoneState=false时，可传入imei信息，穿山甲sdk使用您传入的imei信息
                override fun isCanUseWifiState() = false // 是否允许SDK主动使用ACCESS_WIFI_STATE权限
                override fun isCanUseWriteExternal() = false // 是否允许SDK主动使用WRITE_EXTERNAL_STORAGE权限
                override fun getDevOaid() = null // 开发者可以传入oaid,http://msa-alliance.cn/col.jsp?id=120
                override fun alist() = false // 是否允许SDK主动获取设备上应用安装列表的采集权限
                override fun isCanUseAndroidId() = false // 是否允许SDK主动获取ANDROID_ID
                override fun isCanUsePermissionRecordAudio() = false // 是否允许SDK在申明和授权了的情况下使用录音权限
            })
            .build()
    }

    private fun start() {
        //创建TTAdNative对象
        val mTTAdNative = TTAdSdk.getAdManager().createAdNative(this)

        val dm = DisplayMetrics()
        windowManager.defaultDisplay.getRealMetrics(dm)
        val splashWidthDp = this.px2dp(this.screenWidth)
        val splashWidthPx = this.screenWidth
        val screenHeightPx = this.screenHeight + this.statusBarHeight
        val screenHeightDp = this.px2dp(screenHeightPx)
        var splashHeightDp = 0;
        var splashHeightPx = 0;

        val width90 = resources.getDimensionPixelSize(R.dimen.dp_90_x)
        splashHeightDp = screenHeightDp - this.px2dp(width90)
        splashHeightPx = screenHeightPx - this.dp2px(width90)

        val adSlot = AdSlot.Builder()
            .setCodeId("889214632")
            //不区分渲染方式，要求开发者同时设置setImageAcceptedSize（单位：px）和setExpressViewAcceptedSize（单位：dp ）接口，不同时设置可能会导致展示异常。
            .setExpressViewAcceptedSize(splashWidthDp.toFloat(), splashHeightDp.toFloat()) // 单位是dp
            .setImageAcceptedSize(splashWidthPx, splashHeightPx) // 单位是px
            .setAdLoadType(TTAdLoadType.LOAD)//推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
            .build()

        mTTAdNative.loadSplashAd(adSlot, object : CSJSplashAdListener {
            //开屏素材加载成功
            override fun onSplashLoadSuccess(ad: CSJSplashAd) {
                Log.e("111111","onSplashLoadSuccess")
            }

            //加载开屏素材失败
            override fun onSplashLoadFail(error: CSJAdError) {
                //开发者处理跳转到APP主页面逻辑
                Log.e("111111","onSplashLoadFail")
                FlutterPlugin.toFlutter("loadAdOver","onSplashLoadFail")
            }

            //开屏渲染成功，可以展示开屏
            override fun onSplashRenderSuccess(ad: CSJSplashAd) {
                FlutterPlugin.ad = ad
                val intent = Intent(this@MainActivity,AdActivity::class.java)
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivityForResult(intent,999)
                overridePendingTransition(0, 0);
            }

            override fun onSplashRenderFail(ad: CSJSplashAd, csjAdError: CSJAdError) {
                //开发者处理跳转到APP主页面逻辑
                Log.e("111111","onSplashRenderFail")
                FlutterPlugin.toFlutter("loadAdOver","onSplashRenderFail")
            }
        }, 1500)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 999){
            FlutterPlugin.toFlutter("loadAdOver","onActivityResult")
        } else if (requestCode == 888){
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    FlutterPlugin.toFlutter("showLoading","")
                    val contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE)
                    if (!TextUtils.isEmpty(contentType)) {
                        val filePath = FileUtils.getSaveFile(applicationContext).absolutePath
                        if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT == contentType) {
                            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath)
                        } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK == contentType) {
                            recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath)
                        }
                    }
                }
            }
        }
    }

    // 识别身份证
    private fun recIDCard(idCardSide: String, filePath: String) {
        val param = IDCardParams()
        param.imageFile = File(filePath)
        param.idCardSide = idCardSide // 设置身份证正反面
        param.isDetectDirection = true // 设置方向检测
        param.imageQuality = 20 // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setDetectRisk(true)
        OCR.getInstance(this).recognizeIDCard(param, object : OnResultListener<IDCardResult> {
            override fun onResult(result: IDCardResult?) {
                if (result != null) {
                    "识别结果：$result".loge()
                    val map: MutableMap<String, Any> = HashMap()
                    map["error_message"] = ""
                    map["is_front"] = idCardSide == IDCardParams.ID_CARD_SIDE_FRONT

                    if (idCardSide == IDCardParams.ID_CARD_SIDE_FRONT) { // 人像面
                        // 识别结果：IDCardResult front{direction=0, wordsResultNumber=6, address=山西省武乡县贾豁乡上寺烟村上寺烟14号, idNumber=140429199109298477, birthday=19910929, name=梁宇兴, gender=男, ethnic=汉, RiskType=normal}
                        if (null== result.idNumber || null == result.name || null == result.address || null == result.gender || null == result.ethnic || null == result.birthday){
                            map["error_message"] = "识别失败，请重试"
                            FlutterPlugin.toFlutter("dismissLoading","")
                            return
                        }
//                        vm.idNum.value = "${result.idNumber}"
//                        vm.name.value = "${result.name}"
//                        vm.identityAddress.value = "${result.address}"
//                        vm.sex.value = "${result.gender}"
//                        vm.nation.value = "${result.ethnic}"
//                        vm.birthday.value = "${result.birthday}"
                        map["id_number"] = "${result.idNumber}"
                        map["real_name"] = "${result.name}"
                        map["address"] = "${result.address}"
                        map["gender"] = "${result.gender}"
                        map["nation"] = "${result.ethnic}"
                        map["birthday"] = "${result.birthday}"
                    } else { // 国徽面
                        // 识别结果：IDCardResult back{signDate=20200618, expiryDate=20400618, issueAuthority=武乡县公安局}
                        if (null== result.issueAuthority || null == result.signDate || null == result.expiryDate){
                            map["error_message"] = "识别失败，请重试"
                            FlutterPlugin.toFlutter("dismissLoading","")
                            return
                        }
                        // 发证机关
//                        vm.issueAgency.value = "${result.issueAuthority}"

                        // 有效期,2012.10.01-2022.10.01 或 2017.10.13-长期
                        val startDate = getStrTime("${result.signDate}", "yyyyMMdd", "yyyy.MM.dd")
                        val endDate = if ("${result.expiryDate}".length > 2) {
                            getStrTime("${result.expiryDate}", "yyyyMMdd", "yyyy.MM.dd")
                        } else {
                            "${result.expiryDate}"
                        }
//                        vm.periodValidityDate.value = "${startDate}-$endDate"

                        map["issued_by"] = "${result.issueAuthority}"
                        map["valid_date"] = "${startDate}-$endDate"
                    }

//                    val file = File(filePath)
//                    val bytes = file.readBytes()
//                    var base64 = Base64.encodeToString(bytes, Base64.DEFAULT)
//                    "$base64".loge("111111111111111111111")
//                    var t = base64.replace("\n", "")
//                    t.loge("111111111111111111111")
//                    map["image_base64"] = base64
                    map["image_path"] = filePath
                    FlutterPlugin.toFlutter("scanIdCardOver",map)
                }
            }

            override fun onError(error: OCRError?) {
//                vm.idNum.value = ""
//                vm.name.value = ""
//                vm.identityAddress.value = ""
//                showErrorDialog("${error?.message}",false)
                val map: MutableMap<String, Any> = HashMap()
                map["error_message"] = "${error?.message}"
                FlutterPlugin.toFlutter("scanIdCardOver",map)

                FlutterPlugin.toFlutter("dismissLoading","")
            }
        })
    }

}